#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-03-14 18:23:27
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

# from tornado_mysql import pools, connect
from pymysql import connect
from tornado import gen
from framework.db import conf
from lib import log
from decimal import Decimal

class PDB:

    def __init__(self):
        self.db=conf.database
        self.addconnect()

    def getconnect(self):
        x = 0
        i = ''
        while x <= 3:
            x += 1
            try:
                # i = self.idle.pop()
                # i['conn'].ping()
                # i['index'] += 1
                # if i['index'] > self.index:
                #     i['cur'].close()
                #     i['index'] = 0
                #     i['cur'] = i['conn'].cursor()
                # self.use.append(i)
                self.conn.ping()
                break
            except Exception, e:
                self.addconnect()
                # print e
                continue
        return self.conn, self.cur

    def breakconnect(self, x):
        if x in self.use:
            self.use.remove(x)
            self.idle.append(x)

    def addconnect(self):
        conn = connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=self.db,charset='utf8')
        cur = conn.cursor()
        self.conn = conn
        self.cur = cur


pdb = PDB()


class BaseDb():

    def __init__(self):
        self.cont()

    @gen.coroutine
    def cont(self):
        self.conn, self.cur = pdb.getconnect()

    @gen.coroutine
    def execute(self, query, params=None):

        count = self.cur.execute(query, params)
        # rt_arr = []

        rrr = self.cur.fetchall()
        # for row in rrr:
        #    rt_arr.append(row)

        raise gen.Return(rrr)

    @gen.coroutine
    def executejson(self, query, params=None):
        count = self.cur.execute(query, params)


        results = []
        try:
            feild = self.cur.description
            data = self.cur.fetchone()
            while data:
                res = {}
                n = 0
                for i in feild:
                    if type(data[n]) == unicode:
                        res[i[0]] = data[n]
                    elif data[n] == None:
                        res[i[0]] = ''
                    else:
                        res[i[0]] = str(data[n])
                    n += 1
                results.append(res)
                data = self.cur.fetchone()
        except Exception, e:
            raise
        rt_arr = results

        raise gen.Return(rt_arr)

    def getdata(self, cur):
        results = []
        try:
            feild = cur.description
            data = cur.fetchone()
            while data:
                res = {}
                n = 0
                for i in feild:
                    if type(data[n]) == unicode:
                        res[i[0]] = data[n]
                    elif data[n] == None:
                        res[i[0]] = ''
                    else:
                        res[i[0]] = str(data[n])
                    n += 1
                results.append(res)
                data = cur.fetchone()
        except Exception, e:
            raise
        return results

    @gen.coroutine
    def insertmanay(self, table, params):

        if type(params) != list:
            raise gen.Return('-1')
            return
        elif type(params[0]) != dict:
            raise gen.Return('-1')
            return
        sql = 'INSERT INTO %s %s VALUES %s'
        data = []

        keys = "(" + ",".join(params[0].keys()) + ")"
        feild = '(' + ('%s,'*len(params[0]))[0:-1] +')'
        sql = sql % (table, keys, feild)

        for i in params:
            x = []
            for j in params[0].keys():
                x.append(i[j])
            data.append(tuple(x))

        count = self.cur.executemany(sql, tuple(data))

        raise gen.Return(count)

    @gen.coroutine
    def insert(self, table, params):

        sql = 'INSERT INTO %s %s VALUES %s'
        queryid = 'SELECT LAST_INSERT_ID()'
        keys = "(" + ",".join(params.keys()) + ")"
        values = '(' + ('%s,'*len(params.values()))[0:-1] +')'

        sql = sql % (table, keys, values)

        self.cur.execute(sql, tuple(params.values()))
        self.cur.execute(queryid)
        count = self.cur.fetchall()

        raise gen.Return(count[0][0])

    @gen.coroutine
    def commit(self):
        self.conn.commit()

    # @gen.coroutine
    # def close(self):
    #     self.conn.commit()
    #     self.cur = None
    #     self.conn = None
    #     return pdb.breakconnect(self.x)

    @gen.coroutine
    def upsert(self, query, params=None):
        count = self.cur.execute(query, params)
        raise gen.Return(count)

    @gen.coroutine
    def upsert_commit(self, query, params=None):
        count = self.cur.execute(query, params)
        self.commit()
        raise gen.Return(count)
